<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件夹文本文件读取</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }

        input[type="file"] {
            margin-bottom: 20px;
        }

        button {
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        #result {
            margin-top: 20px;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <!-- 文件选择器，允许选择文件夹 -->
    <input type="file" id="folderInput" webkitdirectory directory multiple>
    <button id="confirmButton">确定</button>
    <div id="result"></div>

    <script>
        // 获取 DOM 元素
        const folderInput = document.getElementById('folderInput');
        const confirmButton = document.getElementById('confirmButton');
        const resultDiv = document.getElementById('result');

        // 为确定按钮添加点击事件监听器
        confirmButton.addEventListener('click', async () => {
            const files = folderInput.files;
            if (files.length === 0) {
                resultDiv.textContent = '请选择一个文件夹';
                return;
            }

            try {
                const allLines = [];
                // 遍历选择的所有文件
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    // 只处理 txt 格式的文件
                    if (file.name.endsWith('.txt')) {
                        const text = await readFileAsText(file);
                        const lines = text.split('\n');
                        allLines.push(...lines);
                    }
                }

                // 这里 allLines 就是存储所有 txt 文件行的数组
                console.log(allLines);
                resultDiv.textContent = '成功';
            } catch (error) {
                console.error('读取文件时出错:', error);
                resultDiv.textContent = '失败';
            }
        });

        // 读取文件内容为文本的函数
        function readFileAsText(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => {
                    resolve(reader.result);
                };
                reader.onerror = () => {
                    reject(reader.error);
                };
                reader.readAsText(file);
            });
        }
    </script>
</body>

</html>